<script setup>
import { ref, onMounted, onBeforeUnmount, h, useCssModule, unref, computed } from 'vue'
import useEventBus from '@/utils/event.bus'
import {
    VideoCameraFilled, Film, CircleCloseFilled,
    Download, Search, Setting, ChatLineRound, Refresh,
    SuccessFilled
} from '@element-plus/icons-vue'
import { exportEventData } from '@/api/export.services'
import {
    fetchEventhandleResult, fetchEventBasic, fetchEventType,
    fetchEventLevel, fetchEventVideo, fetchEventReport,
    fetchEventView
} from '@/api/event.services'
import {
    ElMessage, ElLoading, ElMessageBox, ElTableV2,
    ElButton, ElLink, ElCheckbox, TableV2SortOrder,
    ElTag, ElIcon
} from 'element-plus'
import fileUtils from '@/utils/fileUtils'

import DialogDahuaPlayer from '@/components/DialogDahuaPlayer.vue'
import DrawerHandleEvent from './components/DrawerHandleEvent.vue'
import BatchEventComponents from './components/BatchEventComponents.vue'
import PlayMP4Components from './components/PlayMP4Components.vue'
import ManualInputComponents from './components/ManualInputComponents.vue'
import SearchFormComponents from './components/SearchFormComponents.vue'
const eventBus = useEventBus()
onMounted(() => {
    //事件单个处理
    eventBus.on('eventHandle', getEventHandleFunction)
    //事件的批量处理
    eventBus.on('batchHandle', getEventHandleFunction)
    eventBus.on('eventReal', eventRealFunction)
})
onBeforeUnmount(() => {
    eventBus.off('eventHandle')
    eventBus.off('batchHandle')
    eventBus.off('eventReal')
    // 取消订阅所以事件
    // eventBus.all.clear();
})
const refDialogDahuaPlayer = ref(null)
const refDrawerHandleEvent = ref(null)

const eventRealFunction = data => {
    tableData.value.unshift(data)
}

const getEventHandleFunction = data => {
    getList()
}
const searchForm = ref({
    total: 0,
    page: 1,
    limit: 20,
    status: 1,
    is_virtual: 1
})
const getList = async () => {
    tableData.value = []
    if (searchForm.value.meters1 !== undefined && searchForm.value.meters2 !== undefined) {
        const { meters1, meters2 } = searchForm.value
        if ((meters1 === null) !== (meters2 === null)) {
            ElMessage.error('请输入有效报警米数')
            return
        }

        if (meters1 !== null && meters2 !== null && meters1 >= meters2) {
            ElMessage.error('报警米数开始值不能大于结束值')
            return
        }
    }
    const result = await fetchEventBasic(searchForm.value)
    if (result.code == 1) {
        tableData.value = result.data.data || []
        searchForm.value.total = result.data.total
    }
}
const handleSortChange = ({ column, prop, order }) => {
    searchForm.value.order = order == 'ascending' ? 'asc' : 'desc'
    switch (prop) {
        case 'event_type_name':
            searchForm.value.prop = 'event_type'
            break
        case 'event_level_name':
            searchForm.value.prop = 'event_level'
            break
        case 'status_name':
            searchForm.value.prop = 'status'
            break
        default:
            searchForm.value.prop = prop || 'event_time'
            break
    }
    getList()
}
const tableData = ref([{}])
const handleSizeChange = val => {
    searchForm.value.limit = val
    getList()
}
const handleCurrentChange = val => {
    searchForm.value.page = val
    getList()
}
//删除
// const selectList = ref([])
// const handleSelectionChange = item => {
//     selectList.value = item
// }
const selectList = computed(() => {
    // 过滤 tableData 中 checked 为 true 的行，并提取 event_id
    //return tableData.value.filter(row => row.checked).map(row => row.event_id)
    return tableData.value.filter(row => row.checked)
})
// 获取事件类型
const eventTypeList = ref([])
const getEventType = async () => {
    const result = await fetchEventType()
    if (result.code == 1) {
        eventTypeList.value = result.data
    }
}


// 获取事件等级
const eventLevelList = ref([])
const getEventLevel = async () => {
    const result = await fetchEventLevel()
    if (result.code == 1) {
        eventLevelList.value = result.data
    }
}
const openVideo = async (row, type) => {
    const params = {
        device_id: row.device_id,
        cid: row.cid,
        event_time: row.event_time
    }
    const result = await fetchEventVideo(params)
    if (result.code == 1) {
        if (result.data.length == 0) {
            ElMessage.warning('暂未关联视频')
            return
        }
        const playerData = {
            type: type, // [real: 实时预览, record: 录像回放],
            channels: result.data.map(item => {
                return {
                    channelCode: item.camera_uniq_code,
                    channelName: item.camera_name
                }
            }),
            title: row.event_name
        }
        if (type == 'record') {
            const time = new Date(row.event_time).getTime()
            playerData.startTime = time
            playerData.endTime = time
            playerData.useRecordDuration = true
        }
        refDialogDahuaPlayer.value.open(playerData, result.data)
    }
}
const handleResult = ref([])
const showDrawerHandleEvent = (row) => {
    refDrawerHandleEvent.value?.open(row, handleResult.value)
}
const batchEventComponentsRef = ref(null)
const openBatchHandleBox = () => {
    batchEventComponentsRef.value?.open(selectList.value, handleResult.value)
}

const handleExportFile = async () => {
    // console.log('🚀 ~ handleExportFile ~ selectList.value:', selectList.value)
    // fileUtils().exportFile('event', searchForm.value)
    const loading = ElLoading.service({
        lock: true,
        text: '正在导出...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    try {
        // 向后端请求导出文件
        const response = await exportEventData(searchForm.value)
        // 隐藏“正在导出”提示框
        loading.close()
        // 创建下载链接并触发下载
        const blob = response
        const link = document.createElement('a')
        const fileName = '报警记录' + new Date().toLocaleString() + '.xlsx'  // 你可以动态设置文件名，或从后端获取
        link.href = URL.createObjectURL(blob)
        link.download = fileName  // 设置文件下载的名字
        link.click()  // 触发下载
    } catch (error) {
        // 处理错误
        loading.close()
        ElMessage.error('导出失败')
    }
}
const getHandleResult = async () => {
    const result = await fetchEventhandleResult()
    if (result.code == 1) {
        handleResult.value = result.data
    }
}
getList()
getEventType()
getEventLevel()
getHandleResult()

const playMP4ComponentsRef = ref(null)
const seeMp4 = (row) => {
    playMP4ComponentsRef.value?.open(row)
}
const manualInputComponentsRef = ref(null)
const openManualInput = () => {
    manualInputComponentsRef.value?.open(eventTypeList.value, eventLevelList.value)
}
const emitsInit = (search) => {
    searchForm.value.page = 1
    searchForm.value.total = 0
    searchForm.value.is_virtual = 1
    searchForm.value = { ...searchForm.value, ...search }
    getList()
}
import EventEvaluateComponents from './components/EventEvaluateComponents.vue'
const refEventEvaluateRef = ref(null)
const openEvaluateDrawer = () => {
    refEventEvaluateRef.value?.open(selectList.value)
}
const reportEmergency = async () => {
    try {
        await ElMessageBox.confirm('确定上报应急事件吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        const result = await fetchEventReport({ ids: selectList.value.map(item => item.event_id) })
        if (result.code == 1) {
            ElMessage.success('上报成功')
            getList()
        }
    } catch (error) {
        console.log(error)
    }
}
const visible = ref(false)
const views = ref([])
const initViews = async () => {
    const result = await fetchEventView()
    if (result.code == 1) {
        views.value = result.data
    }
}

const $style = useCssModule()
const SelectionCell = ({
    value,
    intermediate = false,
    onChange,
}) => {
    return h(ElCheckbox, {
        onChange: onChange,
        modelValue: value,
        indeterminate: intermediate,
    })
}
initViews()
const columns = computed(() => {
    return [
        {
            key: 'selection',
            width: 55,
            cellRenderer: ({ rowData }) => {
                const onChange = (value) => (rowData.checked = value)
                return h(SelectionCell, { value: rowData.checked, onChange: onChange })
            },
            headerCellRenderer: () => {
                const _data = unref(tableData)
                const onChange = (value) =>
                (tableData.value = _data.map((row) => {
                    row.checked = value
                    return row
                }))
                const allSelected = _data.every((row) => row.checked)
                const containsChecked = _data.some((row) => row.checked)
                return h(SelectionCell, {
                    value: allSelected,
                    intermediate: containsChecked && !allSelected,
                    onChange: onChange
                })
            }
        },
        {
            key: 'index',
            title: '序号',
            width: 55, // 确保有 width
            align: 'center',
            cellRenderer: ({ rowIndex }) => {
                // 计算序号
                return rowIndex + 1 + (searchForm.value.page - 1) * searchForm.value.limit
            }
        },
        {
            key: 'event_name',
            dataKey: 'event_name',
            title: '事件名称',
            width: 180, // 确保有 width
            sortable: true,
            align: 'center'
        },
        {
            key: 'event_type_name',
            dataKey: 'event_type_name',
            title: '事件类型',
            width: 140, // 确保有 width
            sortable: true,
            align: 'center'
        },
        {
            key: 'event_level_name',
            dataKey: 'event_level_name',
            title: '警情级别',
            width: 120, // 确保有 width
            sortable: true,
            align: 'center'
        },
        // 使用展开运算符和三元表达式来根据条件包含此列
        ...(views.value.includes('type') ? [{
            key: 'type',
            dataKey: 'type',
            title: '事件属性',
            width: 140, // 确保有 width
            sortable: true,
            align: 'center',
            // 如果需要特定格式，可以使用 cellRenderer
            cellRenderer: ({ rowData }) => {
                return h(ElTag, {
                    type: rowData.type == 2 ? 'warning' : 'primary'
                }, () => rowData.type == 2 ? '手工报警' : '设备发生')
            }
        }] : []),
        ...(views.value.includes('is_serious') ? [{
            key: 'is_serious',
            dataKey: 'is_serious',
            title: '应急事件',
            width: 120, // 确保有 width
            sortable: true,
            align: 'center',
            // 如果需要特定格式，可以使用 cellRenderer
            cellRenderer: ({ rowData }) => {
                return rowData.is_serious == 2
                    ? h(ElIcon, { size: '18px', color: '#67C23A' }, () => h(SuccessFilled))
                    : h(ElIcon, { size: '18px', color: '#ccc' }, () => h(CircleCloseFilled))
            }
        }] : []),
        {
            key: 'event_time',
            dataKey: 'event_time',
            title: '发生时间',
            width: 170, // 确保有 width
            sortable: true,
            align: 'center',
            // 如果需要特定格式，可以使用 cellRenderer
            cellRenderer: ({ cellData }) => {
                return h('span', { class: $style['font13'] }, cellData)
            }
        },
        {
            key: 'status_name',
            dataKey: 'status_name',
            title: '事件状态',
            width: 120, // 确保有 width
            sortable: true,
            align: 'center',
            // 需要自定义 cellRenderer 来渲染按钮
            cellRenderer: ({ rowData }) => {
                return h(ElButton, {
                    type: rowData.status == 2 ? 'success' : 'danger',
                    size: 'small'
                }, () => rowData.status_name)
            }
        },
        ...(views.value.includes('recheck_status') ? [{
            key: 'recheck_status',
            dataKey: 'recheck_status',
            title: '复核状态',
            width: 120, // 确保有 width
            sortable: true,
            align: 'center',
            // 如果需要特定格式，可以使用 cellRenderer
            cellRenderer: ({ rowData }) => {
                let tagType = 'info';
                let tagText = '未复核';
                if (rowData.recheck_status == 2) {
                    tagType = 'success';
                    tagText = '复核成功';
                } else if (rowData.recheck_status == 3) {
                    tagType = 'warning';
                    tagText = '复核失败';
                }
                return h(ElTag, { size: 'small', type: tagType }, () => tagText);
            }
        }] : []),
        {
            key: 'device_name',
            dataKey: 'device_name',
            title: '告警源',
            width: 300 // 确保有 width
        },
        ...(views.value.includes('company') ? [{
            key: 'company',
            dataKey: 'company',
            title: '使用单位',
            width: 170
        }] : []),
        ...(views.value.includes('dvc_installation') ? [{
            key: 'dvc_installation',
            dataKey: 'dvc_installation',
            title: '告警源位置',
            width: 170
        }] : []),
        ...(views.value.includes('event_desc') ? [{
            key: 'event_desc',
            dataKey: 'event_desc',
            title: '事件描述',
            width: 170
        }] : []),
        ...(views.value.includes('handle_result') ? [{
            key: 'handle_result',
            dataKey: 'handle_result',
            title: '处理结果',
            width: 120,
            sortable: true,
            align: 'center'
        }] : []),
        ...(views.value.includes('username') ? [{
            key: 'username',
            dataKey: 'username',
            title: '处理用户',
            width: 100,
            align: 'center'
        }] : []),
        ...(views.value.includes('handle_time') ? [{
            key: 'handle_time',
            dataKey: 'handle_time',
            title: '处理时间',
            width: 170,
            align: 'center'
        }] : []),
        {
            key: 'operations',
            title: '操作',
            width: 180, // 确保有 width
            fixed: 'right',
            // 需要自定义 cellRenderer 来渲染操作链接/按钮
            cellRenderer: ({ rowData }) => {
                const links = [
                    // 录像链接
                    rowData.type !== 2
                        ? h(ElLink, {
                            type: 'success',
                            underline: false,
                            icon: VideoCameraFilled,
                            onClick: () => openVideo(rowData, 'record')
                        }, () => '录像')
                        : null,
                    // 详情链接
                    h(ElLink, {
                        type: 'primary',
                        underline: false,
                        icon: Setting, // 根据模板使用 Setting 图标
                        onClick: () => showDrawerHandleEvent(rowData)
                    }, () => '详情'),
                    // MP4链接
                    rowData.videos && rowData.videos.length > 0
                        ? h(ElLink, {
                            type: 'success',
                            underline: false,
                            icon: Film,
                            onClick: () => seeMp4(rowData)
                        }, () => 'MP4')
                        : null
                ].filter(Boolean) // 过滤掉 null 值

                return h('div', { class: $style['table-tools-wrapper'] }, links)
            }
        }
    ]
})
const sortState = ref({
    'event_name': TableV2SortOrder.ASC,
    'event_type_name': TableV2SortOrder.ASC,
    'event_level_name': TableV2SortOrder.ASC,
    'type': TableV2SortOrder.ASC,
    'is_serious': TableV2SortOrder.ASC,
    'event_time': TableV2SortOrder.ASC,
    'status_name': TableV2SortOrder.ASC,
    'recheck_status': TableV2SortOrder.ASC,
    'handle_result': TableV2SortOrder.ASC
})
const onSort = ({ key, order }) => {
    sortState.value[key] = order
    searchForm.value.order = order
    const sort = ['event_name', 'type', 'is_serious', 'event_time', 'recheck_status', 'handle_result']
    if (sort.includes(key)) {
        searchForm.value.prop = key
    } else {
        switch (key) {
            case 'event_type_name':
                searchForm.value.prop = 'event_type'
                break
            case 'event_level_name':
                searchForm.value.prop = 'event_level'
                break
            case 'status_name':
                searchForm.value.prop = 'status'
                break
            default:
                searchForm.value.prop = key || 'event_time'
                break
        }
    }
    getList()
}
</script>
<template>
    <div :class="$style['event-container']">
        <SearchFormComponents @getList="emitsInit" :eventLevelList="eventLevelList" :handleResult="handleResult"
            :eventTypeList="eventTypeList" :fieldsView="views" />
        <div :class="$style['table_container']">
            <div :class="$style['flex-between']">
                <div :class="$style['tools-container']">
                    <el-link type="primary" :underline="false" :icon="Download" :disabled="tableData.length == 0"
                        @click="handleExportFile">
                        导出
                    </el-link>
                    <el-link type="warning" :underline="false" :icon="CircleCloseFilled" @click="openBatchHandleBox"
                        :disabled="selectList.length == 0">
                        批量处理
                    </el-link>
                    <p>已选择{{ selectList.length }}条记录</p>
                    <el-link type="primary" :underline="false" :icon="Search"
                        @click="searchForm.is_virtual == 1 ? searchForm.is_virtual = 2 : searchForm.is_virtual = 1; getList()">
                        {{ searchForm.is_virtual == 1 ? '虚拟撤防事件' : '全部' }}
                    </el-link>
                    <el-link type="primary" :underline="false" :icon="ChatLineRound" :disabled="selectList.length == 0"
                        @click="openEvaluateDrawer">
                        事件评价
                    </el-link>
                    <el-link type="warning" :underline="false" :icon="Refresh" :disabled="selectList.length == 0"
                        @click="reportEmergency">
                        上报应急事件
                    </el-link>
                </div>
                <el-button type="primary" size="small" @click="openManualInput">事件手工录入</el-button>
            </div>
            <div :class="$style['table-wrapper']">
                <el-auto-resizer>
                    <template #default="{ height, width }">
                        <el-table-v2 :columns="columns" :data="tableData" :row-height="50" :width="width"
                            :height="height" v-model:sort-state="sortState" @column-sort="onSort" fixed />
                    </template>
                </el-auto-resizer>
            </div>
            <div :class="$style['flex-end']">
                <el-pagination small background layout="sizes,total,prev, pager, next" :total="searchForm.total"
                    :hide-on-single-page="false" v-model:current-page="searchForm.page"
                    v-model:page-size="searchForm.limit" :page-sizes="[20, 50, 100, 200, 500]"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
    </div>

    <!--播放MP4-->
    <PlayMP4Components ref="playMP4ComponentsRef" />
    <BatchEventComponents ref="batchEventComponentsRef" @success="getList" />
    <DrawerHandleEvent ref="refDrawerHandleEvent" />
    <DialogDahuaPlayer ref="refDialogDahuaPlayer" />
    <ManualInputComponents ref="manualInputComponentsRef" @success="getList" />
    <EventEvaluateComponents ref="refEventEvaluateRef" />
</template>
<style lang="scss" module>
.event-container {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100%;
}

.table_container {
    flex: 1;
    background: #fff;
    border-radius: 8px;
    box-sizing: border-box;
    padding: 0 10px;
    display: flex;
    flex-direction: column;
    margin-top: 10px;
    overflow: hidden;
}

.flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 35px;
}

.tools-container {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    height: 35px;
    align-items: center;

    & [class~='el-link'] {
        margin-right: 15px;
    }

    & p {
        font-size: 12px;
        margin-right: 15px
    }
}

.table-wrapper {
    flex: 1;
}

.table-tools-wrapper {
    width: 100%;
    display: flex;
    align-items: center;

    & [class~='el-link'] {
        margin-right: 15px;
    }
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 35px;
}
</style>